<template>
  <div class="demo">
    <!--  -->
    <h4>使用mockjs随机数据模拟，分页效果</h4>
    <div>
      <input type="text" placeholder="请输入标题" v-model="title" />
      <input type="text" placeholder="请输入内容" v-model="content" />
      <button @click="addData">添加数据</button>
      <button @click="prevPage">上一页</button>
      <button @click="nextPage">下一页</button>
    </div>
    <table width="1000" border>
      <tr>
        <th>序号</th>
        <th>标题</th>
        <th>内容</th>
        <th>时间</th>
        <th>图片</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item) in dataList" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.title }}</td>
        <td>{{ item.content }}</td>
        <td>{{ item.add_time }}</td>
        <td><img :src="item.img_url" /></td>
        <td><button type="button" @click="removeIndex(item.id)">移除</button></td>
      </tr>
    </table>
  </div>
</template>

<script type="text/javascript">
import axios from "axios";
export default {
  data() {
    return {
      title: "",
      content: "",
      pageindex: 1, //起始页
      dataList: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //   获取数据列表
    getList() {
      axios
        .get("/api/get/news", {
          params: {
            pageIndex: this.pageindex,
            pageSize: 10,
          },
        })
        .then((res) => {
          this.dataList = res.data.list;
            console.log(res.data);
        });
    },
    addData() {
      if(this.title.trim() !== "" && this.content.trim() !== ""){
          axios.post('/api/add/news',{
              title:this.title,
              content:this.content
          }).then(res=>{
            console.log(res.data);
          })
      }
    },
    prevPage() {//上一页
      this.pageindex--;
      if (this.pageindex < 1) this.pageindex = 1;
      
      this.getList();
    },
    nextPage() {//下一页
      this.pageindex++;
      this.getList();
    },
    removeIndex(id){//移除
        axios.post('/api/delete/news',{id}).then(res=>{
            console.log(res.data);
        })
    }
  },
};
</script>

<style  scoped>
.demo {
  width: 1000px;
  margin: 0 auto;
}
button {
  width: 80px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  cursor: pointer;
  background-color: cornflowerblue;
  color: white;
  border: none;
  border-radius: 20px;
}
input[type="text"] {
  width: 330px;
  height: 35px;
  border-radius: 5px;
}
</style>
